//
//  HomeTableViewController.swift
//  Weibo8023
//
//  Created by styshy on 15/12/6.
//  Copyright © 2015年 sz. All rights reserved.
//

import UIKit
import SVProgressHUD

let StatusCellNormalId = "StatusCellNormalId"
let StatusCellRetweetedId = "StatusCellRetweetedId"

class HomeTableViewController: VisitorTableViewController {
    
    private lazy var listViewModel = StatusListViewModel()

    override func viewDidLoad() {
        super.viewDidLoad()

        // 判断是否登录，如果没有返回
        if !UserAccountViewModel.sharedUserAccount.userLogin{
            visitorView?.setupInfo(nil, title: "关注一些人，回这里看看有什么惊喜")
            return
        }
        
        prepareTableView()
        
        pulldownLoadData()
        
        // 监听通知
        NSNotificationCenter.defaultCenter().addObserverForName(WBStatusSelectedPhotoNotification, object: nil, queue: nil) {[weak self] (n) -> Void in
            
//            print(n.object)
            /*Weibo8023.StatusPictureView: 0x7fb7d1899200;
            Weibo8023.StatusPictureView: 0x7fb7d1899200;*/
            // 如果字典中的值是可选的，执行方
            guard let indexPath = n.userInfo?[WBStatusSelectedIndexPathNotification] as? NSIndexPath else{
                return
            }
            guard let picUrls = n.userInfo?[WBStatusSelectedPhotoURLsKey] as? [NSURL] else{
                return
            }
            
            guard let cell = n.object as? PhotoBrowserPresentDelegate else{
                return
            }
            
            let vc = PhotoBrowserViewController(indexPath: indexPath, picUrls: picUrls)
            
            print("cell = \(cell)")
            // 设置转场动画类型
            vc.modalPresentationStyle = UIModalPresentationStyle.Custom
            
            // 设置专场动画代理
            vc.transitioningDelegate = self!.photoBrowserAnimator
            
            // 设置转场动画参数
            self?.photoBrowserAnimator.setDelegateParams(cell,dismissDelegate: vc, indexPath: indexPath)
            
            
            self?.presentViewController(vc, animated: true, completion: nil)
            
        }
    }
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    /// 准备tableView
    private func prepareTableView(){
        // 转发
        tableView.registerClass(StatusRetweetedCell.self, forCellReuseIdentifier: StatusCellRetweetedId)
        
        // 原创
        tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier: StatusCellNormalId)
        // 去除tableView的cell分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        tableView.estimatedRowHeight = 400
//        tableView.rowHeight = UITableViewAutomaticDimension
        
        // 下拉刷新
        refreshControl = WBRefreshControl()
        refreshControl?.addTarget(self, action: "pulldownLoadData", forControlEvents: .ValueChanged)
        
    }
    
    // 下拉加载微博数据
    // TODO:上拉刷新，下拉刷新，max_id和since_id
    @objc private func pulldownLoadData(){
        listViewModel.loadStatus(isPullup:true) { (isSuccessed) -> Void in
            
            UIView.animateWithDuration(1.0, animations: { () -> Void in
                var rect = self.pulldownLabel.frame
                rect.origin.y = 100
                self.pulldownLabel.frame = rect
            })
            // 关闭刷新控件
            self.refreshControl?.endRefreshing()
            // 判断是否成功
            if !isSuccessed {
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                return
            }
            
            self.showPulldownTip()
            
            // 刷新数据
            self.tableView.reloadData()
           
        }
    }
    /// 显示下拉刷新提示
    private func showPulldownTip() {
        guard let count = listViewModel.pulldownCount else {
            return
        }
        pulldownLabel.text = (count == 0) ? "没有新微博" : "刷新到 \(count) 条微博"
        
        let height: CGFloat = 44
        let rect = CGRect(x: 0, y: -2 * height, width: view.bounds.width, height: height)
        pulldownLabel.frame = rect
        
        UIView.animateWithDuration(1, animations: {
            self.pulldownLabel.frame = CGRectOffset(rect, 0, 3 * height)
            }) { _ in
                UIView.animateWithDuration(1) { self.pulldownLabel.frame = rect }
        }
    }
    

    
    // 上拉加载微博数据
    @objc private func pullupLoadData(){
        listViewModel.loadStatus(isPullup:false) { (isSuccessed) -> Void in
            // 关闭刷新控件
            self.pullupView.stopAnimating()
            // 判断是否成功
            if !isSuccessed {
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                return
            }
            
            // 刷新数据
            self.tableView.reloadData()
        }
    }

    
    // MARK: - 懒加载控件
    /// 上拉刷新提示视图
    private lazy var pullupView: UIActivityIndicatorView = {
        
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        indicator.color = UIColor.lightGrayColor()
        
        return indicator
    }()
    
    // 设置专场动画
    private lazy var photoBrowserAnimator = PhotoBrowserAnimator()
    
    private lazy var pulldownLabel:UILabel = {
       let label = UILabel(title: "", fontSize: 18, color: UIColor.whiteColor())
        
       label.backgroundColor = UIColor.orangeColor()
        
        self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
        
        return label
    }()

}

// MARK: - 代理方法
extension HomeTableViewController{
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return listViewModel.statusList.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        // 判断使用哪一个cell
        let model = listViewModel.statusList[indexPath.row]
        
        let cell = tableView.dequeueReusableCellWithIdentifier(model.cellId, forIndexPath: indexPath) as! StatusCell
        cell.showingDeleteConfirmation
        cell.viewModel = model
        cell.labelDelegate = self
        
        if indexPath.item == listViewModel.statusList.count - 1 && !pullupView.isAnimating(){
            // 开启动画，加载数据
            pullupView.startAnimating()
            pullupLoadData()
        }
        
        
        return cell
    }
    

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return listViewModel.statusList[indexPath.row].rowHeight
    }
}

extension HomeTableViewController:StatusCellDelegate{
    func statusCellDidClickLabelLinked(text: String) {
        print("text = \(text)")
        guard let url = NSURL(string: text) else{
            return
        }
        let homeVc = HomeWebViewController(url: url)
        // 当push的时候隐藏底部tabBar
        homeVc.hidesBottomBarWhenPushed = true
        navigationController?.pushViewController(homeVc, animated: true)
    }
}
